import { ElMessage } from "element-plus";
import { addProductModelAdd } from "@/api/modules/carType";
import { useDict } from "@/hooks/useDict";
import { useUtile } from "./useUtil";

export const useAdd = (options: any) => {
  const { formData, title, emits, drawerVisible, ruleFormRef } = options;
  const { getDicList, dict, getParentIdKey } = useDict();
  const { transformDataReq } = useUtile();
  // 初始化
  const initData = async () => {
    const data = await getDicList({ parentIdList: dict["batteryInfo"] + "," + dict["configList"] });
    for (let key in data) {
      data[key] = data[key].map((item: any) => {
        return {
          typeId: item.type === 4 ? item.param : item.id,
          typeName: item.name,
          categoryId: item.parentId,
          categoryName: getParentIdKey(item.parentId),
          type: item.type,
          value: "",
          fixed: Number(item.value),
          content: []
        };
      });
      data[key] = data[key].filter(itm => itm.fixed == 1);
      formData.value.propertyList = [...formData.value.propertyList, ...data[key]];
    }
  };
  // 提交事件
  const handleSubmit = () => {
    ruleFormRef.value!.validate(async (valid: boolean) => {
      if (!valid) return;
      try {
        await addProductModelAdd(transformDataReq(formData.value));
        ElMessage.success({ message: `${title.value}车型成功！` });
        emits("refresh");
        drawerVisible.value = false;
      } catch (error) {
        console.log(error);
      }
    });
  };

  return {
    handleSubmit,
    initData
  };
};
